package com.micro.communication;

import java.util.Map;

import com.micro.service.CommonHandler;
import com.micro.util.CommunicatorResponse;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class ApiService extends Service {

	private Handler mHandler = new Handler();

	public void test(){
		
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return apiServiceInterface;
	}

	private ApiServiceInterface.Stub apiServiceInterface = new ApiServiceInterface.Stub() {

		@Override
		public void request(String service, int type,
				ApiServiceListener listener, Map parameters)
				throws RemoteException {
			connect(service, type, listener, parameters);
		}
	};

	private void connect(final String service, final int type,
			final ApiServiceListener listener, final Map map) {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				CommonHandler commonHandler = new CommonHandler();
				CommunicatorResponse result = commonHandler.request(service, type, map);
				final String statusCode = result.getResponseCode();
				final String message = (String) result.getMessage();
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						try {
							listener.requestCompleted(service, type,
									statusCode, message);
						} catch (Exception e) {
                         e.printStackTrace();
						}
					}
				});

			}
		});
		thread.start();
	}

}
